import { MCPTool } from "@aicu/mcp-framework";
import { z } from "zod";

const {
  httpPost,
  downloadCsvData,
  sleep,
  jsonToCsv
} = require('../xhs-browser');

interface NoteInput {
  note_id: string;
  xsec_token: string;
}

interface BatchGetNotesInput {
  notes: NoteInput[];
  download: boolean;
}

class BatchGetNotesTool extends MCPTool<BatchGetNotesInput> {
  name = "批量获取笔记详情";
  description = "批量获取多个小红书笔记的详细数据。用户需要提供笔记ID和xsec_token的数组。可以选择是否导出为CSV文件。适合一次性获取多个笔记的完整信息。";

  schema = {
    notes: {
      type: z.array(z.object({
        note_id: z.string(),
        xsec_token: z.string()
      })),
      description: "笔记列表，每个笔记包含note_id和xsec_token",
    },
    download: {
      type: z.boolean(),
      default: false,
      description: "是否下载导出数据成CSV文件",
    }
  };

  async execute(input: BatchGetNotesInput) {
    const { notes, download } = input;

    try {
      const results: any[] = [];
      let successCount = 0;
      let failCount = 0;

      console.log(`[BatchGetNotes] 开始批量获取 ${notes.length} 个笔记详情...`);

      for (let i = 0; i < notes.length; i++) {
        const { note_id, xsec_token } = notes[i];

        try {
          console.log(`[BatchGetNotes] 正在获取第 ${i + 1}/${notes.length} 个笔记: ${note_id}`);

          const res = await httpPost("/api/sns/web/v1/feed", {
            "source_note_id": note_id,
            "image_formats": [
              "jpg",
              "webp",
              "avif"
            ],
            "extra": {
              "need_body_topic": "1"
            },
            "xsec_source": "pc_feed",
            "xsec_token": xsec_token
          });

          // 格式化数据
          const note = res['items'][0];
          const noteData = {
            note_id: note['id'],
            title: note['noteCard']['title'],
            desc: note['noteCard']['desc'],
            type: note['noteCard']['type'],
            user_name: note['noteCard']['user']['nickname'],
            user_id: note['noteCard']['user']['userId'],
            time: new Date(note['noteCard']['time']).toLocaleString(),
            collected_count: note['noteCard']['interactInfo']['collectedCount'],
            liked_count: note['noteCard']['interactInfo']['likedCount'],
            comment_count: note['noteCard']['interactInfo']['commentCount'],
            share_count: note['noteCard']['interactInfo']['shareCount'],
            images: '',
            video_url: '',
            video_duration: ''
          };

          // 处理图片
          if (note['noteCard']['imageList']) {
            noteData['images'] = note['noteCard']['imageList'].map((i: any) => i['urlDefault']).join(';');
          }

          // 处理视频
          if (note['noteCard']['video']) {
            let v = null;
            for (const key in note['noteCard']['video']['media']['stream']) {
              const vv = note['noteCard']['video']['media']['stream'][key];
              if (vv.length > 0) v = vv[0];
            }
            if (v) {
              noteData['video_url'] = v['masterUrl'];
              noteData['video_duration'] = note['noteCard']['video']['capa']['duration'];
            }
          }

          results.push(noteData);
          successCount++;

          // 延迟避免请求过快
          if (i < notes.length - 1) {
            await sleep(2);
          }
        } catch (err: any) {
          console.error(`[BatchGetNotes] 获取笔记 ${note_id} 失败:`, err.message);
          failCount++;

          // 记录失败的笔记
          results.push({
            note_id: note_id,
            title: '获取失败',
            desc: err.message,
            type: 'error',
            user_name: '',
            user_id: '',
            time: '',
            collected_count: 0,
            liked_count: 0,
            comment_count: 0,
            share_count: 0,
            images: '',
            video_url: '',
            video_duration: ''
          });
        }
      }

      console.log(`[BatchGetNotes] 批量获取完成。成功: ${successCount}, 失败: ${failCount}`);

      if (download) {
        // 转换为CSV格式
        const csvData = jsonToCsv(results, [
          'note_id@笔记ID',
          'title@标题',
          'desc@描述',
          'type@类型',
          'user_name@作者',
          'user_id@作者ID',
          'time@发布时间',
          'collected_count@收藏数',
          'liked_count@点赞数',
          'comment_count@评论数',
          'share_count@分享数',
          'images@图片链接',
          'video_url@视频链接',
          'video_duration@视频时长'
        ]);

        const downloadRes = downloadCsvData(`batch_notes_${notes.length}_${Date.now()}`, csvData);

        if (downloadRes['error']) {
          return `批量获取完成（成功${successCount}个，失败${failCount}个），但保存文件失败：${downloadRes['error']}\n\n数据：\n${JSON.stringify(results, null, 2)}`;
        }

        return `批量获取笔记成功！\n总数：${notes.length}，成功：${successCount}，失败：${failCount}\n文件已保存：${downloadRes['link']}`;
      }

      // 不下载则返回JSON格式
      return JSON.stringify({
        summary: {
          total: notes.length,
          success: successCount,
          fail: failCount
        },
        data: results
      }, null, 2);

    } catch (e: any) {
      return '批量获取笔记失败了！' + e.message;
    }
  }
}

module.exports = BatchGetNotesTool;
